﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.Extension;
using RBS.Core.Model;
using RBS.Web.Controllers;
using Webdiyer.WebControls.Mvc;
using ApiRepository = RBS.Web.Models.ApiRepository;

namespace RBS.Web.Areas.User.Controllers
{
    public class ProfileController : BaseController
    {
        //
        // GET: /User/Profile/

        public ActionResult Index()
        {
            ViewBag.defaultpassword = RBS.Common.RBSKeys.Defaultpassword;
            ViewBag.Status = CurrentUser.Status;
                 DataTable  dt = new RBS.Core.BLL.U_User().GetUserMain(CurrentUser.Id); 
                foreach (DataRow row in dt.Rows)
                {
                    var entity = row.ConvertToEntity<VUserMain>();
                    return View(entity);
                }
               

         /*   ViewBag.Name = CurrentUser.U_Name;
            ViewBag.Mobile = CurrentUser.Mobile;
            ViewBag.Status = CurrentUser.Status;
            ViewBag.Name = CurrentUser.U_Name;
            var bllIntegration = new RBS.Core.BLL.U_User_Integration(); 
            ViewBag.IntegralCount = bllIntegration.GetIntegralCount(CurrentUser.Id); */
            return View();
        }

        public ActionResult Setting()
        {
            var molde = CurrentUser;
            return View(molde);
        }
        [HttpPost]
        public ActionResult Setting(FormCollection collection)
        {
            var molde = CurrentUser;
            molde.U_Name = collection["U_Name"];
            molde.Nick_Name = collection["Nick_Name"];
            molde.Sex = collection["Sex"];
            molde.Birthday = DateTime.Parse(collection["Birthday"]);
            molde.Telphone = collection["Telphone"];
            molde.Mobile = collection["Mobile"];
            molde.QQ = collection["QQ"]; 
            new RBS.Core.BLL.U_User().Update(molde);
            return RedirectToAction("Setting");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult Security()
        {
            var molde = CurrentUser;
            return View(molde);
        }
        [HttpPost]
        public ActionResult Security(FormCollection collection)
        { 
            string OldPassWord = collection["OldPassWord"];
            string Password = collection["Password"];
            string ConfirmPassword = collection["ConfirmPassword"];
            if (OldPassWord != CurrentUser.PassWord)
            {
                return AlertMsg("请输入正确的当前密码！");
            }
            if (ConfirmPassword == CurrentUser.PassWord)
            {
                return AlertMsg("新密码不能跟旧密码相同！");
            }
            CurrentUser.PassWord = ConfirmPassword;
            new RBS.Core.BLL.U_User().Update(CurrentUser);


            return AlertMsg("密码修改成功！");

            return View();
        }

        #region 积分 
        public ActionResult Integral(int id = 1, string kword = null)
        { 
            const int pageSize = 10; 
            var bll = new RBS.Core.BLL.U_User_Integration();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and UserId="+CurrentUser.Id +strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.U_User_Integration>(dt);
            PagedList<RBS.Core.Model.U_User_Integration> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.U_User_Integration>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.U_User_Integration>();
                arts = new PagedList<RBS.Core.Model.U_User_Integration>(list, id, pageSize, totalItems);
            }

            ViewBag.IntegralCount = bll.GetIntegralCount(CurrentUser.Id); 
            return View(arts);
        }

        /// <summary>
        /// 赠送积分
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GiftIntegral(int id)
        {
            var bll = new RBS.Core.BLL.U_User_Integration();
            ViewBag.IntegralCount = bll.GetIntegralCount(CurrentUser.Id); 
             var model = new RBS.Core.Model.U_User_Integration
                {
                    UserId = id
                };

             return View(model);
        }

        [HttpPost]
        public ActionResult GiftIntegral(FormCollection collection)
        {

            var a = collection;
            var GetIntegral = new RBS.Core.Model.U_User_Integration
            {
                    UserId = Convert.ToInt32(collection["UserId"]),
                    Point = Convert.ToInt32(collection["Point"]),
                    PointTime = DateTime.Now,
                    HotelId = CurrentUser.Id,
                    Type =(int)RBSEnums.IntegraType.好友赠送  
            }; 
            var GiftIntegral = new RBS.Core.Model.U_User_Integration
            {
                UserId =  CurrentUser.Id,
                Point = - Convert.ToInt32(collection["Point"]),
                PointTime = DateTime.Now,
                HotelId = Convert.ToInt32(collection["UserId"]),
                Type = (int)RBSEnums.IntegraType.赠送积分
            };
            var bll = new RBS.Core.BLL.U_User_Integration();
            bll.Add(GetIntegral);
            bll.Add(GiftIntegral); 
            return RedirectToAction("GiftIntegral");
        }

        #endregion

        #region 认证

        public ActionResult Verify()
        {
            var model = CurrentUser; 
            
            return View(model);
        }
        [HttpPost]
        public JsonResult SendMsg(string mobile)
        { 

            var ret=new JsonReturnMessages();
            var yzm = RBS.Common.Utils.Number(6); 
            Session["yzm"] = yzm;
            Session.Timeout = 1;
            string content = "【呷饭网】验证码：" + yzm + ",尊敬的食客，您正在进行个人身份认证!"; 
            string msg = string.Empty;
            bool result = new RBS.Core.BLL.SmsMessage().Send(mobile.Trim(), content, 2, out msg);
            if (result)
            {  
                ret.Msg = msg;
                ret.IsSuccess = true;
            }
            else
            {
                ret.Msg = msg + yzm;
                ret.IsSuccess = false;
            }
            return Json(ret);
        }
        [HttpPost]
        public ActionResult Verify(FormCollection collection)
        {

            var yzm2 = collection["yzm"];
            var yzm1 = Session["yzm"].ToString();
            var uid = Convert.ToInt32(collection["Id"]); 
            var model = CurrentUser; 
            model.Status = 3; 
            new RBS.Core.BLL.U_User().Update(model);
            if (yzm2 == yzm1)
            {
                var integration = new U_User_Integration
                {
                    Point = 200,
                    PointTime = DateTime.Now,
                    Type = 3,
                    UserId = uid,
                    HotelId = -1
                };
                new RBS.Core.BLL.U_User_Integration().Add(integration); 
            } 
            return RedirectToAction("Verify");
        }

          [HttpPost]
        public JsonResult EditMobile(int id,string mobile)
        {  
            var ret=new JsonReturnMessages(); 
               JsonData jsonData = ApiRepository.Get("api/User/Register?type=mobile&value=" + mobile + ""); 
              if (jsonData.Success == false)
              {
                  ret.Msg = "修改失败，此手机已经注册。";
                  ret.IsSuccess = false;
              }
              else
              {
                  var bll = new RBS.Core.BLL.U_User();
                  var model = bll.GetModel(id);
                  model.Mobile = mobile;
                  model.Status = 1;
                  model.Id = id;
                  bll.Update(model); 
                  bool result = bll.Update(model);
                  if (result)
                  {
                      ret.Msg = "修改成功，请重新认证。";
                      ret.IsSuccess = true;
                      Session["User"] = model;
                  }
                  else
                  {
                      ret.Msg = "修改失败";
                      ret.IsSuccess = false;
                  }
                  
              } 
            return Json(ret);
        } 
        
        #endregion


        #region 好友 
        public ActionResult Friends(int id = 1, string kword = null)
        {
            const int pageSize = 10;
        
            var bll = new RBS.Core.BLL.U_Friends();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and UserId=" + CurrentUser.Id + strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.U_Friends>(dt);
            PagedList<RBS.Core.Model.U_Friends> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.U_Friends>();
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }
        public ActionResult Fans(int id = 1, string kword = null)
        {
            const int pageSize = 10;

            var bll = new RBS.Core.BLL.U_Friends();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = " and FriendId=" + CurrentUser.Id + strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.U_Friends>(dt);
            PagedList<RBS.Core.Model.U_Friends> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.U_Friends>();
                arts = new PagedList<RBS.Core.Model.U_Friends>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }
        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FriendsEdit(int id = 0)
        {
            var model = new RBS.Core.Model.U_Friends();
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.U_Friends();
                model = bll.GetModel(id);
            }
            ViewData.Model = model;
            return View();
        }
        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FriendsEdit(FormCollection collection)
        {
            var ret = new JsonReturnMessages();
            if (collection["FriendName"] == CurrentUser.U_Uid)
            {
                const string msg = "不能添加自己为好友！";
                return Content("$.dialog.alert('" + msg + "');", "application/x-javascript");
            }

            if (Convert.ToInt32(collection["FriendId"]) == 0)
            {
                var mobile = collection["FriendName"];
                string content = string.Format("尊敬的朋友您的好友{0}邀请您使用呷饭网。点击下面地址下载呷饭网客户端:{1}", CurrentUser.U_Name, "http://www.xiafanwang.com/");
                string msg = string.Empty;
                bool result = new RBS.Core.BLL.SmsMessage().Send(mobile.Trim(), content, 2, out msg);
                if (result)
                {
                    ret.Msg = msg; 
                }
                else
                {
                    ret.Msg = msg + content; 
                }
                var stcript = "$.dialog.alert('" + ret.Msg + "！');";
                return Content(stcript, "application/x-javascript");  
                return View();
            }

            var model = new RBS.Core.Model.U_Friends
            {
                    UserId = CurrentUser.Id ,
                    FriendId = Convert.ToInt32(collection["FriendId"]),
                    FriendName =  collection["FriendName"],
                    CreateTime =DateTime.Now,
                    Remark =  collection["Remark"],
            };

            var bll = new RBS.Core.BLL.U_Friends();
            if (bll.ExistsFriendId(model.FriendId,model.UserId))
            {
                const string stcript = "$.dialog.alert('当前用户已经是您好友！');";
                return Content(stcript, "application/x-javascript");
            }
            if (bll.Add(model)>0)
            {
                var stcript = "$.dialog.alert('添加成功！');window.location.href='" + @Url.Action("Friends") + "'";
                return Content(stcript, "application/x-javascript"); 
            }
            return View();
        }

        /// <summary>
        /// 查询好友
        /// </summary>
        /// <param name="term"></param>
        /// <returns></returns>
        public ActionResult QuickSearch(string term)
        {
            //u_name like '%" + term + "%' or nick_name like '%" + term + "%' or  U_Uid like '%"+term+"%' or
            var singers = new RBS.Core.BLL.U_User().GetModelList(" ( Mobile like '%"+term+"%')")
                .Select(a => new
                    {
                        a.Id,
                       a.U_Uid,
                       a.Nick_Name,
                       a.U_Name,
                       a.Mobile,
                        a.Email,
                       a.QQ
                    });
            return Json(singers, JsonRequestBehavior.AllowGet);  
        }
         
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteFriend(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages(); 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.U_Friends().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("Friends", "Profile");
            return Json(ret);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Guanzhu(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    var model = new RBS.Core.Model.U_Friends
                        {
                            UserId = CurrentUser.Id,
                            FriendId = Convert.ToInt32(id),
                            CreateTime = DateTime.Now,
                            Remark ="",
                            FriendName = new RBS.Core.BLL.U_User().GetModelByCache(Convert.ToInt32(id)).Mobile
                        };
                    new RBS.Core.BLL.U_Friends().Add(model);
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "关注成功！";
                return Json(ret);
            }
            ret.IsSuccess = true;
            ret.Msg = "关注成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("Friends", "Profile");
            return Json(ret);
        }

        #endregion
    }
}
